﻿using System.Web;
using System.Web.UI;
using Cms.Web.Framework.Infrastructure;

namespace Cms.Web.Framework.Controls
{
    public class ApplicationPageContent : Control, INamingContainer
    {
        public void RenderPublishedContent(RequestDetails details)
        {
            if (details.Page != null)
            {
                string html = details.Page.GetPublishedContentHtml(ID, details.Locale.ID);
                ContentParser.Parse(html, this, details.RequestedUrl);
            }
        }
        
        public void RenderContent(RequestDetails details)
        {
            string html;
            if (details.Page != null && details.ContentTranslationVersion != null)
            {
                html = details.Page.GetContentHtml(ID, details.Locale.ID, details.ContentTranslationVersion.Timestamp);
            }
            else if (!details.AllowContentEditing || details.Page == null)
            {
                html = "Lorem ipsum...";
            }
            else
            {
                html = "&nbsp;";
            }
            ContentParser.Parse(html, this, details.RequestedUrl);
        }

        public void RenderEditAreaLinks(RequestDetails details)
        {
            if (details.Page == null)
            {
                return;
            }
            var content = details.Page.GetContent(ID);
            if (content != null && content.DeniedAdministratorGroups.Contains(details.Administrator.Group))
            {
                return;
            }
            var areaMenu = new EditAreaMenu();
            areaMenu.ContentType = "ApplicationPageContent";
            areaMenu.AreaID = ID;
            areaMenu.MasterTemplateID = details.MasterTemplate.ID;
            areaMenu.LocaleID = details.Locale.ID;
            areaMenu.PageID = details.Page.ID;
            areaMenu.SaveReturnUrl =
                HttpContext.Current.Server.UrlEncode("EditApplicationPage.aspx?id=" + details.Page.ID + "&tab=content");
            areaMenu.CancelReturnUrl =
                HttpContext.Current.Server.UrlEncode("EditApplicationPage.aspx?id=" + details.Page.ID + "&tab=content");
            areaMenu.VersionID = details.ContentTranslationVersion != null
                                     ? details.ContentTranslationVersion.ID
                                     : -1;
            Controls.Add(areaMenu);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            writer.WriteBeginTag("div");
            writer.WriteAttribute("class", "cmsApplicationPageContent");
            writer.Write(">");
            base.Render(writer);
            writer.WriteEndTag("div");
        }
    }
}